<template>
  <div class="deptAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button" v-if="!contactAddShow">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(deptFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon>返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-if="!contactAddShow"
        :class="contactAddShow ? 'customInfoUpClass' : 'customInfoDownClass'"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title"
            >{{
              pageType === "detail" ? "" : pageType === "add" ? "新增" : "编辑"
            }}部门信息</span
          >
        </template>
        <div class="dept-info">
          <el-form
            :model="deptForm"
            ref="deptFormRef"
            :rules="queryRules"
            label-width="100"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="所属公司" prop="companyId">
                  <el-select
                    v-model="deptForm.companyId"
                    placeholder="请选择所属公司"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="dict in companyList"
                      :key="dict.companyId"
                      :label="dict.companyName"
                      :value="dict.companyId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="上级部门">
                  <el-tree-select
                    style="width: 100%"
                    ref="refSelect"
                    v-model="deptForm.parentId"
                    :data="deptOptions"
                    :props="{
                      value: 'deptId',
                      label: 'deptName',
                      children: 'children',
                    }"
                    value-key="deptId"
                    placeholder="选择上级部门"
                    check-strictly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门类型" prop="deptType">
                  <el-select
                    v-model="deptForm.deptType"
                    placeholder="请选择部门类型"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="dict in companyDeptList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门名称" prop="deptName">
                  <el-input
                    v-model="deptForm.deptName"
                    placeholder="请输入部门名称"
                  />
                </el-form-item>
              </el-col>
        
              <el-col :span="6">
                <el-form-item label="一级部门" prop="firstLevel">
                  <el-select
                    v-model="deptForm.firstLevel"
                    placeholder="是否一级部门"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="dict in firstLevelList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="负责人" prop="userId">
                  <el-select
                    v-model="deptForm.userId"
                    style="width: 300px"
                    placeholder="请选择负责人"
                    clearable
                    filterable
                    popper-class="custom-dropdown"
                    placement="bottom-end"
                  >
                    <div class="dropdown-slot">
                      <span
                        style="
                          float: left;
                          color: #8492a6;
                          margin: 0 0px 0 20px;
                        "
                        >人员姓名</span
                      >
                      <span style="margin: 0 90px 0 57px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </div>
                    <div class="scrollable-options">
                      <el-option
                        v-for="item in userList"
                        :key="item.userId"
                        :label="item.nickName"
                        :value="item.userId"
                      >
                        <span
                          style="
                            display: inline-block;
                            width: 80px;
                            float: left;
                            color: #8492a6;
                          "
                          >{{ item.nickName }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            margin: 0 15px 0 23px;
                            color: #8492a6;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                          "
                          >{{
                            item.phonenumber ? item.phonenumber : "--"
                          }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            font-size: 13px;
                            margin: 0 0px 0 0px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.postName ? item.postName : "--" }}
                        </span>
                        <span
                          style="
                            display: inline-block;
                            margin: 0 0px 0 0px;
                            font-size: 13px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.deptName ? item.deptName : "--" }}
                        </span>
                      </el-option>
                    </div>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="false">
                <el-form-item label="负责人" prop="leader">
                  <el-input
                    v-model="deptForm.leader"
                    placeholder="请输入负责人"
                    maxlength="24"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话" prop="phone">
                  <el-input
                    v-model="deptForm.phone"
                    placeholder="请输入联系电话"
                    maxlength="11"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="deptForm.email"
                    placeholder="请输入邮箱"
                    maxlength="50"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="显示排序" prop="orderNum">
                  <el-input-number
                    v-model="deptForm.orderNum"
                    controls-position="right"
                    :min="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门状态">
                  <el-radio-group v-model="deptForm.status">
                    <el-radio
                      v-for="dict in sys_normal_disable"
                      :key="dict.value"
                      :label="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import {
  addDept,
  delDept,
  getDept,
  listDept,
  updateDept,
  selectCompanyByList,
} from "@/api/system/dept";

const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_show_hide } = proxy.useDict(
  "sys_show_hide",
  "sys_normal_disable"
);
import { getDictsApi } from "@/api/dict";
import { listUserAll } from "@/api/system/user";

import { ElMessage, ElMessageBox } from "element-plus";
import SvgIcon from "@/components/SvgIcon";
import IconSelect from "@/components/IconSelect";
import { ClickOutside as vClickOutside } from "element-plus";
const emit = defineEmits([
  "deptAddShow",
  "update:deptAddShow",
  "updateEvaluateAddShow",
  "refreshList",
]);
const props = defineProps({
  pageType: {
    type: String,
    default: "add",
  },
});
const activeNames = ref(["1", "2", "3"]);
const deptFormRef = ref();
const detailInfoShow = ref(false);
const deptOptions = ref([]);
const deptRef = ref(null);
const showChooseIcon = ref(false);
const iconSelectRef = ref(null);

const refSelect = ref();
const deptFormTemplate = {
  deptId: undefined,
  parentId: undefined,
  deptName: undefined,
  orderNum: 0,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: "0",
  companyId: null,
  deptType: null,
  userId:null,
  firstLevel:null
};
const data = reactive({
  deptForm: JSON.parse(JSON.stringify(deptFormTemplate)),
  queryRules: {
    parentId: [
      { required: true, message: "上级部门不能为空", trigger: "blur" },
    ],
    deptName: [
      { required: true, message: "部门名称不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "显示排序不能为空", trigger: "blur" },
    ],
    companyId: [
      { required: true, message: "请选择所属部门", trigger: "change" },
    ],
    deptType: [
      { required: true, message: "请选择部门类型", trigger: "change" },
    ],
    userId: [
      { required: true, message: "负责人不能为空", trigger: "change" },
    ],
    firstLevel: [
      { required: true, message: "一级部门不能为空", trigger: "change" },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phone: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
  contactTypeList: [],
  templateList: [],
  provinceList: [],
  cityList: [],
  areaList: [],
  userList: [],
  deptList: [],
});
const { deptForm, queryRules, templateList } = toRefs(data);
const contactAddShow = ref(false);
//所属公司数据
const companyList = ref([]);
//部门类型数据
const companyDeptList = ref([]);

const userList = ref([]);

//部门类型数据
const firstLevelList = ref([]);
/** 查询菜单下拉树结构 */
function getTreeselect() {
  deptOptions.value = [];
  listDept().then((response) => {
    const dept = { deptId: 0, deptName: "主类目", children: [] };
    dept.children = proxy.handleTree(response.data, "deptId");
    deptOptions.value.push(dept);
  });
}

// 保存
const handleAddSave = async (deptFormRef) => {
  if (!deptFormRef) return;
  await deptFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          if (deptForm.value.deptId != undefined) {
            updateDept(deptForm.value).then((res) => {
              emit("update:deptAddShow", false);
              emit("refreshList", true);
              ElMessage.success(res.msg);
              deptForm.value = JSON.parse(JSON.stringify(deptForm));
            });
          } else {
            addDept(deptForm.value).then((res) => {
              emit("update:deptAddShow", false);
              emit("refreshList", true);
              ElMessage.success(res.msg);
              deptForm.value = JSON.parse(JSON.stringify(deptForm));
            });
          }
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};

// 返回
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("updateEvaluateAddShow", false);
    emit("update:deptAddShow", false);
    deptForm.value = JSON.parse(JSON.stringify(deptFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("updateEvaluateAddShow", false);
        emit("update:deptAddShow", false);
        deptForm.value = JSON.parse(JSON.stringify(deptFormTemplate));
      })
      .catch(() => {});
  }
};

async function getDicts() {
  // 部门类型
  await getDictsApi("erp_dept_type").then((res) => {
    if (res.code === 200) {
      companyDeptList.value = res.data;
    }
  });

  await getDictsApi("sys_dept_firstlevel").then((res) => {
    if (res.code === 200) {
      firstLevelList.value = res.data;
    }
  });

  await listUserAll().then((res) => {
    console.log(res)
    if (res.rows.length > 0) {
      userList.value = res.rows;
    }
    console.log(userList)
  });
  // await getDictsApi("contract_template_type").then((res) => {
  //   if (res.code === 200) {
  //     templateList.value = res.data;
  //   }
  // });
  // 所属公司
  await selectCompanyByList().then((res) => {
    if (res.length > 0) {
      companyList.value = res;
    }
  });
}

// 处理父id
const handleParentId = (id) => {
  if (id) {
    deptForm.value.parentId = id;
  } else {
    deptForm.value.parentId = 0;
  }
};

// 处理详情信息
const handleDetailInfo = async (deptId) => {
  try {
    detailInfoShow.value = true;
    getDept(deptId).then((response) => {
      deptForm.value = response.data;
      detailInfoShow.value = false;
    });
  } catch (error) {
    detailInfoShow.value = false;
  }
};
onMounted(() => {
  getDicts();
  getTreeselect();
  // getDeptTreeselect();
  // if (props.pageType === "add") {
  nextTick(() => {
    refSelect.value.focus(); // 聚焦
  });
  // }
});

defineExpose({
  handleDetailInfo,
  handleParentId,
});
</script>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  background-color: #f8faff;
}
.deptAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  // .search-button {
  //   position: absolute;
  //   top: -45px;
  //   right: 60px;
  //   display: flex;
  //   .btn {
  //     display: flex;
  //     justify-content: center;
  //     align-items: center;
  //     width: 90px;
  //     height: 34px;
  //     padding: 10px;
  //     // margin-right: 20px;
  //     font-size: 14px;
  //     border-radius: 4px;
  //     user-select: none;
  //     cursor: pointer;
  //   }
  //   .btn.save {
  //     color: #fff;
  //     background: rgba(67, 207, 124, 1);
  //     border: none;
  //     &:hover {
  //       background: rgba(67, 207, 124, 0.85);
  //     }
  //   }

  //   .btn.add {
  //     .btn.add {
  //       border: none;
  //       color: #fff;
  //       background: rgba(255, 159, 0, 1);
  //       &:hover {
  //         background: rgba(255, 159, 0, 0.85);
  //       }
  //     }
  //   }

  //   .btn.back {
  //     border: none;
  //     color: #fff;
  //     background: rgba(255, 159, 0, 1);
  //     &:hover {
  //       background: rgba(255, 159, 0, 0.85);
  //     }
  //   }
  //   .btn.direction {
  //     border: none;
  //     color: #fff;
  //     background: rgba(153, 153, 153, 1);
  //     &:hover {
  //       background: rgba(153, 153, 153, 0.85);
  //     }
  //   }

  //   .icon {
  //     margin-right: 6px;
  //   }
  // }
  .circle {
    margin: 0 10px 0 20px;
    width: 6px;
    height: 6px;
    background: #007cef;
    border-radius: 50%;
  }
  .collapse-title {
    font-weight: bold;
    font-size: 16px;
  }
  .el-collapse,
  .el-collapse-item__wrap {
    border: none;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }
  .dept-info {
    padding: 20px 10px 5px 10px;
    background-color: #fafafa;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
    .table-operate {
      display: flex;
      justify-content: space-around;
      .table-icon {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }
    }
  }
  .button-position {
    top: 6px;
    right: 30px;
  }
  :deep(.el-input__inner) {
    height: 34px;
  }
  .customInfoUpClass {
    -webkit-animation: customInfoDown 0.8s ease-out;
  }
  .customInfoDownClass {
    -webkit-animation: customInfoDown 0.8s ease-out;
  }

  .contactInfoUpClass {
    -webkit-animation: contactInfoUp 0.8s ease-out;
  }
  .contactInfoDownClass {
    -webkit-animation: contactInfoUp 0.8s ease-out;
  }
  @-webkit-keyframes customInfoUp {
    0% {
      opacity: 0;
      -webkit-transform: translateY(80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
  @-webkit-keyframes customInfoDown {
    0% {
      opacity: 0;
      -webkit-transform: translateY(-80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
  @-webkit-keyframes contactInfoUp {
    0% {
      opacity: 0;
      -webkit-transform: translateY(80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
}
</style>
